import { Injectable, Logger } from '@nestjs/common';
import { DataSource } from 'typeorm';
import * as fs from 'fs';
import * as path from 'path';
import { join } from 'path';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class InitDataService {
  private readonly logger = new Logger(InitDataService.name);

  constructor(
    private dataSource: DataSource,
    private configService: ConfigService,
  ) {
  }

  /**
   * 执行SQL文件初始化数据
   * @param fileName 文件名，不带路径和后缀
   * @returns
   */
  async executeSqlFile(fileName: string): Promise<{ success: boolean; message: string }> {
    try {
      const filePath = join(__dirname, '../../config/db', `${fileName}.sql`);

      // 检查文件是否存在
      if (!fs.existsSync(filePath)) {
        return {
          success: false,
          message: `SQL文件不存在: ${filePath}`,
        };
      }

      // 读取SQL文件内容
      const sqlContent = fs.readFileSync(filePath, 'utf-8');

      // 执行SQL
      const queryRunner = this.dataSource.createQueryRunner();
      await queryRunner.connect();
      await queryRunner.startTransaction();

      try {
        // 分割SQL语句（简单分割，假设每条语句以分号结尾）
        const sqlStatements = sqlContent
          .split(';')
          .filter(sql => sql.trim().length > 0)
          .map(sql => sql.trim() + ';');

        for (const sql of sqlStatements) {
          await queryRunner.query(sql);
        }

        // 提交事务
        await queryRunner.commitTransaction();

        return {
          success: true,
          message: `成功执行SQL文件: ${fileName}`,
        };
      } catch (error) {
        // 回滚事务
        await queryRunner.rollbackTransaction();
        this.logger.error(`执行SQL文件失败: ${error.message}`, error.stack);

        return {
          success: false,
          message: `执行SQL文件失败: ${error.message}`,
        };
      } finally {
        // 释放queryRunner
        await queryRunner.release();
      }
    } catch (error) {
      this.logger.error(`初始化数据失败: ${error.message}`, error.stack);
      return {
        success: false,
        message: `初始化数据失败: ${error.message}`,
      };
    }
  }

  /**
   * 初始化所有数据
   */
  async initAllData(): Promise<{ success: boolean; message: string; details?: any[] }> {
    const sqlFiles = [
      'sys_dept',
      'sys_dict',
      'sys_dict_data',
      'sys_menu',
      'sys_post',
      'sys_roles',
      'sys_users',
      'sys_user_roles',
      'sys_user_posts',
      'sys_role_menus',
      'sys_api',
      'sys_api_ignore',
      'sys_casbin_rule',
    ];

    const results = [];
    let hasError = false;

    // 依次执行每个SQL文件
    for (const file of sqlFiles) {
      const result = await this.executeSqlFile(file);
      results.push({
        file,
        ...result,
      });

      if (!result.success) {
        hasError = true;
      }
    }

    return {
      success: !hasError,
      message: hasError ? '部分数据初始化失败' : '所有数据初始化成功',
      details: results,
    };
  }

  /**
   * 获取可用的SQL文件列表
   */
  async getSqlFiles(): Promise<string[]> {
    const dataDir = path.join(process.cwd(), 'data');

    if (!fs.existsSync(dataDir)) {
      return [];
    }

    const files = fs.readdirSync(dataDir)
      .filter(file => file.endsWith('.sql'))
      .map(file => file.replace('.sql', ''));

    return files;
  }
}
